package com.thx.user.action;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.BaseAction;
import com.thx.common.util.CaptchaUtil;
import com.thx.common.util.RandomTextUtil;

/**
 * @author balance
 * 
 */

@Namespace("/user")
@Controller(value = "captchaAction")
@Scope("prototype")
public class CaptchaAction extends BaseAction {

	private static final long serialVersionUID = -1529061756890704287L;

	/** 宽度 */
	private int width = 60;
	/** 高度 */
	private int height = 20;
	/** 验证码类型 */
	private int type = 1;
	/** 图片类型 */
	private int imageType = 1;

	/** 验证码长度默认4 */
	private int length = 4;

	public String execute() {
		return captcha();
	}

	public String captcha() {

		HttpServletResponse response = getResponse();
		HttpSession session = getSession();

		response.setHeader("P3P", "CP=CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		try {
			// 创建验证码内容
			String[] key = RandomTextUtil.createRandomText(RandomTextUtil.Type.alphanumeric, length);

			session.setAttribute(CaptchaUtil.CAPTCHA_NAME, key[0]);

			// 创建验证码图片
			BufferedImage image = createImage(imageType, width, height, key[1]);

			OutputStream os = response.getOutputStream();
			ImageIO.write(image, "JPEG", os);
			os.flush();
			os.close();
			os = null;
			response.flushBuffer();
		} catch (IllegalStateException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public BufferedImage createImage(int imageType, int width, int height, String randomText) {
		return CaptchaUtil.creatCaptcha(width, height, randomText);
	}

	public int getImageType() {
		return imageType;
	}

	public void setImageType(int imageType) {
		this.imageType = imageType;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

}
